import {
	defineStore
} from 'pinia';
import app from './app';

const permission = defineStore({
	id: 'permission',
	state: () => ({
		// 底部弹窗参数
		bottomShow: true,
		bottomId: 'ACCESS_FINE_LOCATION',
		// 是否已授权  0 未授权  1已授权  -1 临时拒绝  -2 永久拒绝
		locate: 0,
		// 被禁止的权限（临时权限也会加入进来）
		permissionList: [],
		// 申请权限id
		permissionID: '',
		// 成功回调函数
		success: null,
		// 失败回调函数
		fail: null,
		// 是否显示自定义弹窗
		showPopup: false,
		pagesList: [],
		temporary: null,
		audio: 0,
	}),
	getters: {},
	actions: {
		requestPermissions() {
			console.log('requestPermissions','调用了');
			const permanent = (list) => {
				let lists = list.map(item => {
					return item.split('android.permission.')[1]
				})
				if (!this.examine(lists)) {
					this.setPermission(lists)
				}
				// 执行穿过的失败回调函数
				this.fail && this.fail()
				this.openLose()
			}

			// 辅助函数：准备 Android 权限字符串
			const prepareAndroidPermissions = (permissions) => {
				return permissions.map(permission => `android.permission.${permission}`);
			};

			// 处理 Android 权限的检查和请求
			const handleAndroidPermissions = () => {
				const permissions = this.permissionID.split(',');
				const permissionIDs = prepareAndroidPermissions(permissions);

				Promise.all(permissions.map(permission => this.getcheckPermission(permission)))
					.then(results => {
						if (results.some(result => result.checkResult == -1)) {
							if (!this.examine(permissions)) {
								this.showPopup = true;
							}
						}
					})
					.catch(err => {
						console.error(err);
					});

				plus.android.requestPermissions([...permissionIDs], e => {
					// 关闭权限申请目的自定义弹框
					this.showPopup = false;
					//已授权
					if (e.granted.length > 0) {
						// 去删除禁用列表中存在的数据
						if (this.examine(permissions)) {
							this.deletePermission(permissions)
						}
						// 执行传过来的成功回调函数
						this.success && this.success()
					}
					// 临时拒绝
					if (e.deniedPresent.length > 0) {
						permanent(e.deniedPresent)
					}
					// 已被永久禁用
					if (e.deniedAlways.length > 0) {
						permanent(e.deniedAlways)
					}

					if (this.permissionID === 'RECORD_AUDIO') {
						switch (true) {
							case e.granted.length > 0:
								this.audio = 1;
								break;
							case e.deniedPresent.length > 0:
								this.audio = -1;
								break;
							case e.deniedAlways.length > 0:
								this.audio = -2;
								break;
						}
					}

					if (this.permissionID === 'ACCESS_FINE_LOCATION') {
						switch (true) {
							case e.granted.length > 0:
								this.locate = 1;
								this.bottomShow = false;
								break;
							case e.deniedPresent.length > 0:
								this.locate = -1;
								break;
							case e.deniedAlways.length > 0:
								this.locate = -2;
								break;
						}
					}
				});
			};

			// #ifdef APP-PLUS
			if (plus.os.name === 'Android') {
				handleAndroidPermissions();
			} else {
				handleIOSPermissions(this.permissionID);
			}
			// #endif
		},
		getcheckPermission(id) {
			return new Promise((resolve, reject) => {
				plus.android.checkPermission('android.permission.' + id,
					granted => {
						resolve({
							type: id,
							checkResult: granted.checkResult
						})
					},
					error => {
						reject()
					}
				);
			})
		},
		// 设置权限
		setPermission(data) {
			data.map(item => {
				this.permissionList.push(item)
			})
		},
		// 检测当前权限是否被禁用
		examine(data) {
			return data.some(item => {
				return this.permissionList.includes(item)
			})
		},
		// 删除被禁用列表里面存在的权限
		deletePermission(data) {
			let indexList = data.map(item => {
				let i = this.permissionList.findIndex(value => value === item)
				return i
			})
			indexList.map(item => {
				this.permissionList.splice(item, 1)
			})
		},
		openLose() {
			uni.showModal({
				title: '温馨提示',
				content: '还没有该权限，立即去设置开启？',
				cancelText: "取消",
				confirmText: "去设置",
				showCancel: true,
				confirmColor: '#000',
				cancelColor: '#666',
				success: (res) => {
					if (res.confirm) {
						this.goSetting();
					}
				}
			})
		},
		goSetting() {
			if (plus.os.name == "iOS") {
				var UIApplication = plus.ios.import("UIApplication");
				var application2 = UIApplication.sharedApplication();
				var NSURL2 = plus.ios.import("NSURL");
				var setting2 = NSURL2.URLWithString("app-settings:");
				application2.openURL(setting2);
				plus.ios.deleteObject(setting2);
				plus.ios.deleteObject(NSURL2);
				plus.ios.deleteObject(application2);
			} else {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			}
		},
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'permission-store',
		}, ],
	},
});

export default permission;